package com.example.testappwidget.view

import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import com.example.testappwidget.utils.LogUtil

/*
 *Author: chinadragon
 *Time: 2024/4/3
 * https://blog.csdn.net/raolulu/article/details/120869901
 */
class MyWidgetHostView : ViewGroup {
    private val Tag = this.javaClass.simpleName

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    private val cellCoordinate = IntArray(2)
    var mHeight = 0
    var mWidth = 0

    /**
     * 当用户添加某个WidgetHostView,使用此方法，将其添加到MyWidgetHostView容器中
     */
    private fun addInScreen(child: View, width: Int, height: Int) {
        val parms = MyLayoutParams(width, height)
        parms.x = cellCoordinate[0]
        parms.y = cellCoordinate[1]
        mWidth = parms.width
        mHeight = parms.height
        addView(child, parms)
    }


    /**
     * 测量当前view下所有childView的高度和宽度
     */
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        LogUtil.i(Tag, "onMeasure 回调")

        val count = childCount
        var lp: MyLayoutParams? = null
        for (index in 0 until count){
            val child: View = getChildAt(index)
            lp = child.layoutParams as MyLayoutParams
            child.measure(MeasureSpec.makeMeasureSpec(lp.width,MeasureSpec.EXACTLY),MeasureSpec.makeMeasureSpec(lp.height,MeasureSpec.EXACTLY))
        }

        setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec))

    }

    /**
     * 将每个childView按照MyLayoutParams定义重新布局
     */
    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        LogUtil.i(Tag, "onLayout 回调")
        val childCount = getChildCount()
        var lp: MyLayoutParams? = null
        for (index in 0 until  childCount){
            val child: View = getChildAt(index)
            lp = child.layoutParams as MyLayoutParams
            child.layout(lp.x, lp.y, lp.x + lp.width, lp.y + lp.height)
        }


    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        LogUtil.i(Tag, "onSizeChanged 回调")

    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        LogUtil.i(Tag, "onDraw 回调")

    }

    data class MyLayoutParams(var width: Int, var height: Int) : ViewGroup.LayoutParams(width, height) {
        var x: Int = 0
        var y: Int = 0
    }
}